$(document).ready(init);

// JsSip SIP User Agent
var sipUA;

// Configuration parameters
var isHiddenFieldsIncluded = false;
var sipDomainName  = "@officesip.local";

// Initial panel setup
function init() {
    $("#registerButton").click(register);
    $("#unregisterButton").click(unregister).hide();
    $("#connectButton").click(connect);
    $("#connectButton").attr("disabled", "disabled");
    $("#disconnectButton").click(disconnect).hide();
    $("#sendText").click(sendMessage);
    $("#sendText").attr("disabled", "disabled");
    $("#migrateButton").click(migrate);
    $("#migrateButton").attr("disabled", "disabled");
    $("#acceptButton").attr("disabled", "disabled");
    var formFields = localStorage.getItem("formFields");
    if (formFields != null) {
        restoreFormFields(formFields);
        localStorage.removeItem("formFields");
    }
    var hiddenFields = localStorage.getItem("hiddenFields");
    if (hiddenFields != null && isHiddenFieldsIncluded == true) {
        restoreFormFields(hiddenFields);
        localStorage.removeItem("hiddenFields");
    }
}

// Register on SIP server
function register() {
    var sipRegistrarAddress = "ws://" + $("#registrarAddress").val();
    var id = $("#pc1_id").val();
    var uri = 'sip:' + id + sipDomainName;
    var configuration = {
        'ws_servers': sipRegistrarAddress,
        'uri': uri,
        'register': true,
        'trace_sip': true
    };
    sipUA = new JsSIP.UA(configuration);

    sipUA.on('registered', function (e) {
        $("#registrationInfo").html(" Registered, ID: " + id);
    });

    sipUA.on('unregistered', function (e) {
        $("#registrationInfo").html(" Not registered");
    });

    sipUA.on('registrationFailed', function (e) {
        $("#registrationInfo").html(" Not registered");
    });

    sipUA.on('newRTCSession', function (e) {
        var request = e.data.request;
        var session = e.data.session;
        if (e.data.originator === "local") {
            log("Connecting to " + $("#pc2_id").val() + " ...");
        } else {
            var display_name = request.from.display_name || request.from.uri.user;
            log("Incoming request from " + display_name);

            var eventHandlers = {
                'progress': function (e) { log("> in progress"); },
                'failed': function (e) { log("> failed!"); $("#connectButton").removeAttr("disabled"); },
                'started': channelEstablished,
                'ended': channelClosed
            };

            var options = {
                'eventHandlers': eventHandlers
            };

            session.answer(options);
        }
    });
    $("#registerButton").hide();
    $("#unregisterButton").show();
    $("#connectButton").removeAttr("disabled");
    sipUA.start();
    return false;
}

// Unregister on SIP server
function unregister() {
    $("#registerButton").show();
    $("#unregisterButton").hide();
    $("#connectButton").show().attr("disabled", "disabled");
    $("#disonnectButton").hide();
    $("#sendText").attr("disabled", "disabled");
    $("#migrateButton").attr("disabled", "disabled");
    $("#acceptButton").attr("disabled", "disabled");
    sipUA.stop();
    return false;
}

// Initialize RTCDatachannel
function connect() {
    $("#connectButton").attr("disabled", "disabled");
    $("#datawindow").empty();

    var id = $("#pc2_id").val();
    var uri = 'sip:' + id + sipDomainName;

    var eventHandlers = {
        'progress': function (e) { log("> in progress"); },
        'failed': function (e) { log("> failed!"); $("#connectButton").removeAttr("disabled"); },
        'started': channelEstablished,
        'ended': channelClosed
    };

    var options = {
        'eventHandlers': eventHandlers
    };

    sipUA.connectDataChannel(uri, options);
    return false;
}

// on RTCSession connected function
var channelEstablished = function (e) {
    $("#sendText").removeAttr("disabled");
    $("#migrateButton").removeAttr("disabled");
    $("#connectButton").removeAttr("disabled").hide();
    $("#disconnectButton").show();
    log("> connected!");
    sipUA.dataChannel.onmessage = function (e) {
        var message = JSON.parse(e.data);
        if (message.type === "text") {
            log("received: " + message.text);
        } else {
            executeMigration(message);
        }
    }
}

// Close RTCDatachannel
function disconnect() {
    sipUA.closeDataChannel();
    return false;
}

// on RTCSession ended function
var channelClosed = function (e) {
    $("#disconnectButton").hide();
    $("#connectButton").show();
    $("#sendText").attr("disabled", "disabled");
    $("#migrateButton").attr("disabled", "disabled");
    $("#acceptButton").attr("disabled", "disabled");
    log("> closed!");
}

// send Text chat message
function sendMessage() {
    log("<p>sent: " + $("#pcInput").val() + "</p>");

    var message = {
        type: "text",
        text: $("#pcInput").val()
    }
    var messageString = JSON.stringify(message);
    sipUA.dataChannel.send(messageString);
    return false;
}

// Migrate session main function
function migrate() {
    var _url = $(location).attr('href');
    var _cookies = getCookies();
    var _hiddenFields = getHiddenFields();
    var _formFields = getFormFields();
    var message = {
        type: "session",
        cookies: _cookies,
        formFields: _formFields,
        hiddenFields: (isHiddenFieldsIncluded == true) ? _hiddenFields : null,
        url: _url
    }
    var messageString = JSON.stringify(message);
    sipUA.dataChannel.send(messageString);
    disconnect();
    return false;
}

function getCookies() {
    var _cookies = document.cookie;
    return _cookies;
}

function getFormFields() {
    var formFields = $(".rtc-migrate");
    var result = [];
    for (var i = 0; i < formFields.length; i++) {
        var obj = {
            id: formFields[i].id,
            value: escape(formFields[i].value)
        };
        result.push(obj);
    }
    return result;
}

function getHiddenFields() {
    var hiddenFields = $("input:hidden");
    var result = [];
    for (var i = 0; i < hiddenFields.length; i++) {
        var obj = {
            id : hiddenFields[i].id,
            value : escape(hiddenFields[i].value)
        };
        result.push(obj);
    }
    return result;
}

// restore session main function
function executeMigration(message) {
    var newCookies = message.cookies.split(';');
    for (var i = 0; i < newCookies.length; i++) {
        var pair = newCookies[i].split("=");
        document.cookie = pair[0] + "=" + unescape(pair[1]);
    }
    var formFields = message.formFields;
    var hiddenFields = message.hiddenFields;
    localStorage.setItem("formFields", JSON.stringify(formFields));
    localStorage.setItem("hiddenFields", JSON.stringify(hiddenFields));
    $(location).attr('href', message.url);    
    return false;
}

function restoreFormFields(data) {
    var formFields = JSON.parse(data);
    for (var i = 0; i < formFields.length; i++) {
        $("#" + formFields[i].id).val(unescape(formFields[i].value));
    }
}

// Output text to log window
function log(text) {
    $("#datawindow").append("<p>" + text + "</p>");
}